package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.EndangeredWildlife;
import com.wildlife.springboot.mapper.service.ImageUploadService;
import com.wildlife.springboot.service.IEndangeredWildlifeService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/endangeredWildlife")
public class EndangeredWildlifeController {

    @Resource
    private IEndangeredWildlifeService endangeredWildlifeService;

    @Resource
    private ImageUploadService imageUploadService;


    //新增和修改
    @PostMapping
    public Result save(@RequestBody EndangeredWildlife endangeredWildlife){
        //新增或更新
        return Result.success(endangeredWildlifeService.saveOrUpdate(endangeredWildlife));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(endangeredWildlifeService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(endangeredWildlifeService.removeByIds(ids));
    }

    // 获取所有濒危野生动物信息的接口
    @GetMapping("/all")
    public Result findAnimalAll() {
        List<EndangeredWildlife> wildlifeList = endangeredWildlifeService.list();
        if (wildlifeList != null && !wildlifeList.isEmpty()) {
            return Result.success(wildlifeList);
        } else {
            return Result.fail("未找到任何濒危野生动物信息");
        }
    }

    @GetMapping
    public Result findAll() {
        return Result.success(endangeredWildlifeService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(endangeredWildlifeService.getById(id));
    }

    @GetMapping("/chineseName/{chineseName}")
    public Result findOne(@PathVariable String chineseName) {
        QueryWrapper<EndangeredWildlife> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chinese_name", chineseName);
        return Result.success(endangeredWildlifeService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String chineseName,
                           @RequestParam(defaultValue = "") String scientificName,
                           @RequestParam(defaultValue = "") String phylum,
                           @RequestParam(defaultValue = "") String animalClass,
                           @RequestParam(defaultValue = "") String animalOrder) {
        QueryWrapper<EndangeredWildlife> queryWrapper = new QueryWrapper<>();

        // 根据不同条件动态拼接查询
        if (!"".equals(chineseName)) {
            queryWrapper.like("chinese_name", chineseName);
        }
        if (!"".equals(scientificName)) {
            queryWrapper.like("scientific_name", scientificName);
        }
        if (!"".equals(phylum)) {
            queryWrapper.like("phylum", phylum);
        }
        if (!"".equals(animalClass)) {
            queryWrapper.like("animal_class", animalClass);
        }
        if (!"".equals(animalOrder)) {
            queryWrapper.like("animal_order", animalOrder);
        }

        // 分页查询
        return Result.success(endangeredWildlifeService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }



    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<EndangeredWildlife> list = endangeredWildlifeService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("chineseName", "中文名");
        writer.addHeaderAlias("englishName", "英文名");
        writer.addHeaderAlias("scientificName", "学名");
        writer.addHeaderAlias("nickname", "别名");
        writer.addHeaderAlias("commonName", "俗名");
        writer.addHeaderAlias("kingdom", "界");
        writer.addHeaderAlias("phylum", "门");
        writer.addHeaderAlias("animalClass", "纲");
        writer.addHeaderAlias("subclass", "亚纲");
        writer.addHeaderAlias("animalOrder", "目");
        writer.addHeaderAlias("animalFamily", "科");
        writer.addHeaderAlias("genus", "属");
        writer.addHeaderAlias("identifyingFeature", "鉴别特征");
        writer.addHeaderAlias("appearance", "外形");
        writer.addHeaderAlias("furColor", "毛色");
        writer.addHeaderAlias("color", "颜色");
        writer.addHeaderAlias("limb", "四肢");
        writer.addHeaderAlias("skull", "头骨");
        writer.addHeaderAlias("teeth", "牙齿");
        writer.addHeaderAlias("weight", "体重");
        writer.addHeaderAlias("length", "体长");
        writer.addHeaderAlias("mouthPeak", "嘴峰");
        writer.addHeaderAlias("tarsometatarsalLength", "跗蹠长");
        writer.addHeaderAlias("tail", "尾长");
        writer.addHeaderAlias("wingLength", "翅长");
        writer.addHeaderAlias("fullLength", "全长");
        writer.addHeaderAlias("headLength", "头长");
        writer.addHeaderAlias("headBodyLength", "头体长");
        writer.addHeaderAlias("bodyHeight", "体高");
        writer.addHeaderAlias("bodyWidth", "体宽");
        writer.addHeaderAlias("hindFootLength", "后足长");
        writer.addHeaderAlias("earLength", "耳长");
        writer.addHeaderAlias("skullLength", "颅全长");
        writer.addHeaderAlias("skullBaseLength", "颅基长");
        writer.addHeaderAlias("palatalLength", "腭长");
        writer.addHeaderAlias("snoutLength", "吻长");
        writer.addHeaderAlias("intermolarWidth", "臼齿间宽");
        writer.addHeaderAlias("zygomaticWidth", "颧宽");
        writer.addHeaderAlias("orbitalWidth", "眶间宽");
        writer.addHeaderAlias("backHeadWidth", "后头宽");
        writer.addHeaderAlias("upperDentitionLength", "上齿列长");
        writer.addHeaderAlias("lowerDentitionLength", "下齿列长");
        writer.addHeaderAlias("abdominalScale", "腹鳞");
        writer.addHeaderAlias("buccalScale", "颊鳞");
        writer.addHeaderAlias("anteriorTemporalScale", "前颞鳞");
        writer.addHeaderAlias("posteriorTemporalScale", "后颞鳞");
        writer.addHeaderAlias("dorsalScale", "背鳞");
        writer.addHeaderAlias("caudalScale", "尾下鳞");
        writer.addHeaderAlias("snoutScale", "吻鳞");
        writer.addHeaderAlias("internasalScale", "鼻间鳞");
        writer.addHeaderAlias("supraocularScale", "眼上鳞");
        writer.addHeaderAlias("supraorbitalScale", "眶上鳞");
        writer.addHeaderAlias("nasalScale", "鼻鳞");
        writer.addHeaderAlias("prefossaScale", "窝前鳞");
        writer.addHeaderAlias("subfossaScale", "窝下鳞");
        writer.addHeaderAlias("upperLipScale", "上唇鳞");
        writer.addHeaderAlias("lowerLipScale", "下唇鳞");
        writer.addHeaderAlias("temporalScale", "颞区鳞");
        writer.addHeaderAlias("superiorCiliaryScale", "上睫鳞");
        writer.addHeaderAlias("caudalVentralScale", "尾腹鳞");
        writer.addHeaderAlias("dorsalArmorLength", "背甲长");
        writer.addHeaderAlias("dorsalArmorWidth", "背甲宽");
        writer.addHeaderAlias("dorsalArmorHeight", "背甲高");
        writer.addHeaderAlias("dorsalDiscLength", "背盘长");
        writer.addHeaderAlias("dorsalDiscWidth", "背盘宽");
        writer.addHeaderAlias("dorsalDiscHeight", "背盘高");
        writer.addHeaderAlias("prefrontalScale", "前额鳞");
        writer.addHeaderAlias("vertebralShield", "椎盾");
        writer.addHeaderAlias("costalShield", "肋盾");
        writer.addHeaderAlias("borderShield", "缘盾");
        writer.addHeaderAlias("shoulderHeight", "肩高");
        writer.addHeaderAlias("honking", "鸣声");
        writer.addHeaderAlias("habitat", "栖息地");
        writer.addHeaderAlias("diet", "食性");
        writer.addHeaderAlias("reproductivePeriod", "繁殖期");
        writer.addHeaderAlias("pregnancyPeriod", "妊娠期");
        writer.addHeaderAlias("lifetime", "寿命");
        writer.addHeaderAlias("ovulationPeriod", "产卵期");
        writer.addHeaderAlias("eggCount", "窝卵数");
        writer.addHeaderAlias("eggWeight", "卵重");
        writer.addHeaderAlias("eggDiameter", "卵径");
        writer.addHeaderAlias("incubationPeriod", "孵化期");
        writer.addHeaderAlias("incubationRate", "孵化率");
        writer.addHeaderAlias("nest", "巢穴");
        writer.addHeaderAlias("nestDiameter", "巢径");
        writer.addHeaderAlias("nestSpacing", "巢间距");
        writer.addHeaderAlias("sexualMaturityTime", "性成熟时间");
        writer.addHeaderAlias("hibernant", "冬眠期");
        writer.addHeaderAlias("migrationTime", "迁徙时间");
        writer.addHeaderAlias("activity", "活动");
        writer.addHeaderAlias("naturalEnemy", "天敌");
        writer.addHeaderAlias("reproduction", "繁殖");
        writer.addHeaderAlias("populationSize", "种群数量");
        writer.addHeaderAlias("populationTrend", "种群趋势");
        writer.addHeaderAlias("biotope", "生境");
        writer.addHeaderAlias("ecosystem", "生态系统");
        writer.addHeaderAlias("domesticDistribution", "国内分布");
        writer.addHeaderAlias("foreignDistribution", "国外分布");
        writer.addHeaderAlias("endemicSpecie", "是否特有种");
        writer.addHeaderAlias("subspeciesDifferentiation", "亚种分化");
        writer.addHeaderAlias("protectedLevel", "国家重点保护野生动物等级");
        writer.addHeaderAlias("iucn", "IUCN红色名录");
        writer.addHeaderAlias("source", "来源");
        writer.addHeaderAlias("categoryCharacteristic", "种类特征");
        writer.addHeaderAlias("feature", "形态特征");
        writer.addHeaderAlias("distributionArea", "分布区域");
        writer.addHeaderAlias("mainComponents", "主要成分");
        writer.addHeaderAlias("effect", "功效");
        writer.addHeaderAlias("classification", "分类");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("珍稀濒危动物", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("中文名", "chineseName");
        reader.addHeaderAlias("英文名", "englishName");
        reader.addHeaderAlias("学名", "scientificName");
        reader.addHeaderAlias("别名", "nickname");
        reader.addHeaderAlias("俗名", "commonName");
        reader.addHeaderAlias("界", "kingdom");
        reader.addHeaderAlias("门", "phylum");
        reader.addHeaderAlias("纲", "animalClass");
        reader.addHeaderAlias("亚纲", "subclass");
        reader.addHeaderAlias("目", "animalOrder");
        reader.addHeaderAlias("科", "animalFamily");
        reader.addHeaderAlias("属", "genus");
        reader.addHeaderAlias("鉴别特征", "identifyingFeature");
        reader.addHeaderAlias("外形", "appearance");
        reader.addHeaderAlias("毛色", "furColor");
        reader.addHeaderAlias("颜色", "color");
        reader.addHeaderAlias("四肢", "limb");
        reader.addHeaderAlias("头骨", "skull");
        reader.addHeaderAlias("牙齿", "teeth");
        reader.addHeaderAlias("体重", "weight");
        reader.addHeaderAlias("体长", "length");
        reader.addHeaderAlias("嘴峰", "mouthPeak");
        reader.addHeaderAlias("跗蹠长", "tarsometatarsalLength");
        reader.addHeaderAlias("尾长", "tail");
        reader.addHeaderAlias("翅长", "wingLength");
        reader.addHeaderAlias("全长", "fullLength");
        reader.addHeaderAlias("头长", "headLength");
        reader.addHeaderAlias("头体长", "headBodyLength");
        reader.addHeaderAlias("体高", "bodyHeight");
        reader.addHeaderAlias("体宽", "bodyWidth");
        reader.addHeaderAlias("后足长", "hindFootLength");
        reader.addHeaderAlias("耳长", "earLength");
        reader.addHeaderAlias("颅全长", "skullLength");
        reader.addHeaderAlias("颅基长", "skullBaseLength");
        reader.addHeaderAlias("腭长", "palatalLength");
        reader.addHeaderAlias("吻长", "snoutLength");
        reader.addHeaderAlias("臼齿间宽", "intermolarWidth");
        reader.addHeaderAlias("颧宽", "zygomaticWidth");
        reader.addHeaderAlias("眶间宽", "orbitalWidth");
        reader.addHeaderAlias("后头宽", "backHeadWidth");
        reader.addHeaderAlias("上齿列长", "upperDentitionLength");
        reader.addHeaderAlias("下齿列长", "lowerDentitionLength");
        reader.addHeaderAlias("腹鳞", "abdominalScale");
        reader.addHeaderAlias("颊鳞", "buccalScale");
        reader.addHeaderAlias("前颞鳞", "anteriorTemporalScale");
        reader.addHeaderAlias("后颞鳞", "posteriorTemporalScale");
        reader.addHeaderAlias("背鳞", "dorsalScale");
        reader.addHeaderAlias("尾下鳞", "caudalScale");
        reader.addHeaderAlias("吻鳞", "snoutScale");
        reader.addHeaderAlias("鼻间鳞", "internasalScale");
        reader.addHeaderAlias("眼上鳞", "supraocularScale");
        reader.addHeaderAlias("眶上鳞", "supraorbitalScale");
        reader.addHeaderAlias("鼻鳞", "nasalScale");
        reader.addHeaderAlias("窝前鳞", "prefossaScale");
        reader.addHeaderAlias("窝下鳞", "subfossaScale");
        reader.addHeaderAlias("上唇鳞", "upperLipScale");
        reader.addHeaderAlias("下唇鳞", "lowerLipScale");
        reader.addHeaderAlias("颞区鳞", "temporalScale");
        reader.addHeaderAlias("上睫鳞", "superiorCiliaryScale");
        reader.addHeaderAlias("尾腹鳞", "caudalVentralScale");
        reader.addHeaderAlias("背甲长", "dorsalArmorLength");
        reader.addHeaderAlias("背甲宽", "dorsalArmorWidth");
        reader.addHeaderAlias("背甲高", "dorsalArmorHeight");
        reader.addHeaderAlias("背盘长", "dorsalDiscLength");
        reader.addHeaderAlias("背盘宽", "dorsalDiscWidth");
        reader.addHeaderAlias("背盘高", "dorsalDiscHeight");
        reader.addHeaderAlias("前额鳞", "prefrontalScale");
        reader.addHeaderAlias("椎盾", "vertebralShield");
        reader.addHeaderAlias("肋盾", "costalShield");
        reader.addHeaderAlias("缘盾", "borderShield");
        reader.addHeaderAlias("肩高", "shoulderHeight");
        reader.addHeaderAlias("鸣声", "honking");
        reader.addHeaderAlias("栖息地", "habitat");
        reader.addHeaderAlias("食性", "diet");
        reader.addHeaderAlias("繁殖期", "reproductivePeriod");
        reader.addHeaderAlias("妊娠期", "pregnancyPeriod");
        reader.addHeaderAlias("寿命", "lifetime");
        reader.addHeaderAlias("产卵期", "ovulationPeriod");
        reader.addHeaderAlias("窝卵数", "eggCount");
        reader.addHeaderAlias("卵重", "eggWeight");
        reader.addHeaderAlias("卵径", "eggDiameter");
        reader.addHeaderAlias("孵化期", "incubationPeriod");
        reader.addHeaderAlias("孵化率", "incubationRate");
        reader.addHeaderAlias("巢穴", "nest");
        reader.addHeaderAlias("巢径", "nestDiameter");
        reader.addHeaderAlias("巢间距", "nestSpacing");
        reader.addHeaderAlias("性成熟时间", "sexualMaturityTime");
        reader.addHeaderAlias("冬眠期", "hibernant");
        reader.addHeaderAlias("迁徙时间", "migrationTime");
        reader.addHeaderAlias("活动", "activity");
        reader.addHeaderAlias("天敌", "naturalEnemy");
        reader.addHeaderAlias("繁殖", "reproduction");
        reader.addHeaderAlias("种群数量", "populationSize");
        reader.addHeaderAlias("种群趋势", "populationTrend");
        reader.addHeaderAlias("生境", "biotope");
        reader.addHeaderAlias("生态系统", "ecosystem");
        reader.addHeaderAlias("国内分布", "domesticDistribution");
        reader.addHeaderAlias("国外分布", "foreignDistribution");
        reader.addHeaderAlias("是否特有种", "endemicSpecie");
        reader.addHeaderAlias("亚种分化", "subspeciesDifferentiation");
        reader.addHeaderAlias("国家重点保护野生动物等级", "protectedLevel");
        reader.addHeaderAlias("IUCN红色名录", "iucn");
        reader.addHeaderAlias("来源", "source");
        reader.addHeaderAlias("种类特征", "categoryCharacteristic");
        reader.addHeaderAlias("形态特征", "feature");
        reader.addHeaderAlias("分布区域", "distributionArea");
        reader.addHeaderAlias("主要成分", "mainComponents");
        reader.addHeaderAlias("功效", "effect");
        reader.addHeaderAlias("分类", "classification");

        List<EndangeredWildlife> list = reader.readAll(EndangeredWildlife.class);
        endangeredWildlifeService.saveBatch(list);
        return true;
    }

    // 上传图片接口
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = imageUploadService.uploadImage(file);
            // 返回相对路径而不是完整的本地文件路径
            return Result.success(url);
        } catch (Exception e) {
            return Result.fail("上传失败");
        }
    }

    @DeleteMapping("/deleteImage/{filePath:.+}")
    public Result deleteImage(@PathVariable String filePath) {
        try {
            // 设置图片存储的根路径
            String basePath = "D:\\Program Files (x86)\\IdeaProjects\\Wildlife\\uploads\\";
            // 拼接完整路径
            String fullPath = basePath + filePath;

            File file = new File(fullPath);
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    return Result.success("图片删除成功");
                } else {
                    return Result.fail("图片删除失败");
                }
            } else {
                return Result.fail("图片不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("图片删除时发生错误：" + e.getMessage());
        }
    }




    // 获取卡片数据
    @GetMapping("/cards")
    public Result findAllForCards() {
        List<EndangeredWildlife> list = endangeredWildlifeService.list();
        return Result.success(list);
    }
}
